package com.peng.utils;

import com.peng.entity.Department;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 生成部门树
 */
public class DepartmentTree {
    /**
     * 生成部门树列表
     *
     * @param departmentList 部门列表
     * @param pid            父部门id
     * @return
     */
    public static List<Department> makeDepartmentTree(List<Department> departmentList, Long pid) {
        // 创建集合保存部门信息
        List<Department> list = new ArrayList<>();
        // 判断部门列表是否为空，如果不为空则使用部门列表，否则创建集合对象
        Optional.ofNullable(departmentList).orElse(new ArrayList<Department>())
                .stream().filter(new Predicate<Department>() {
                    @Override
                    public boolean test(Department department) {
                        return department != null && department.getPid() == pid;
                    }
                }).forEach(new Consumer<Department>() {
                    @Override
                    public void accept(Department item) {
                        Department department = new Department();
                        // 复制属性
                        BeanUtils.copyProperties(item, department);
                        // 获取到每一个item的下级部门，递归生成部门树
                        List<Department> children = makeDepartmentTree(departmentList, item.getId());
                        // 设置子部门
                        department.setChildren(children);
                        // 将部门对象添加到部门集合中
                        list.add(department);
                    }
                });
        return list;
    }
}
